import React, { useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  Switch,
  TouchableOpacity,
  ScrollView,
  Platform,
} from 'react-native';
import RNFS from 'react-native-fs';
import SafeTabBarWrapper from '../components/SafeTabBarWrapper';
import {
  requestLocationPermission,
  getCurrentPosition,
  wgs84ToGcj02,
  getLocationInfo,
  hasAskedLocationPermission,
  markLocationPermissionAsked,
  convertWgs84ToGcj02ViaAmap,
  checkLocationPermission,
} from '../utils/locationUtils';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { ToastManager } from '../components/Toast';
import voiceService from '../services/voiceService';
import { COLORS, SHADOWS } from '../styles/constants';

const AUTO_PLAY_KEY = 'auto_voice_play_enabled';
const LOCATION_STATUS_KEY = 'location_service_status';
const TTS_VOICE_KEY = 'tts_voice_name';

const SettingItem = ({ title, description, children }) => (
  <View style={styles.settingItem}>
    <View style={styles.settingTextWrapper}>
      <Text style={styles.settingTitle}>{title}</Text>
      {description ? (
        <Text style={styles.settingDescription}>{description}</Text>
      ) : null}
    </View>
    {children}
  </View>
);

export default function SettingsScreen() {
  const [locationEnabled, setLocationEnabled] = useState(false);
  const [locStatus, setLocStatus] = useState('尚未获取定位权限');
  const [autoPlayEnabled, setAutoPlayEnabled] = useState(true);
  const [cacheSize, setCacheSize] = useState('计算中...');
  const [showLocationService, setShowLocationService] = useState(false);
  const [selectedVoice, setSelectedVoice] = useState('4');
  const [showVoicePicker, setShowVoicePicker] = useState(false);

  React.useEffect(() => {
    (async () => {
      const auto = await AsyncStorage.getItem(AUTO_PLAY_KEY);
      setAutoPlayEnabled(auto !== 'false');

      // 读取保存的声音配置
      const savedVoice = await AsyncStorage.getItem(TTS_VOICE_KEY);
      if (savedVoice) {
        setSelectedVoice(savedVoice);
        voiceService.setBaiduTtsConfig({ voiceName: savedVoice });
      }

      // 检查实际的系统定位权限状态
      const hasPermission = await checkLocationPermission();
      const asked = await hasAskedLocationPermission();
      const status = await AsyncStorage.getItem(LOCATION_STATUS_KEY);

      if (hasPermission) {
        // 如果系统权限已授予，显示已启用
        setLocationEnabled(true);
        if (status === 'enabled') {
          setLocStatus('已启用定位，可获取附近景区');
        } else {
          setLocStatus('定位权限已授予');
          // 更新 AsyncStorage 状态，避免下次重复检查
          await AsyncStorage.setItem(LOCATION_STATUS_KEY, 'enabled');
        }
        setShowLocationService(false);
        // 标记已询问过权限
        if (!asked) {
          await markLocationPermissionAsked();
        }
      } else if (asked) {
        // 用户拒绝了权限
        setLocationEnabled(false);
        setLocStatus('定位权限被拒绝，请前往系统设置开启');
        setShowLocationService(true);
      } else {
        // 尚未询问权限
        setLocationEnabled(false);
        setLocStatus('尚未获取定位权限');
        setShowLocationService(false);
      }
    })();
    refreshCacheSize();
  }, []);

  const handleToggleAutoPlay = async value => {
    setAutoPlayEnabled(value);
    await AsyncStorage.setItem(AUTO_PLAY_KEY, value ? 'true' : 'false');
    ToastManager.info(value ? '已开启自动播讲解' : '已关闭自动播讲解');
  };

  // 声音选项
  const voiceOptions = [
    { id: '0', name: '度小美', description: '温柔女声，标准音色' },
    { id: '1', name: '度小宇', description: '成熟男声，标准音色' },
    { id: '3', name: '度逍遥', description: '情感男声，磁性声音' },
    { id: '4', name: '度丫丫', description: '情感女声，自然亲切' },
    { id: '5', name: '度小娇', description: '可爱女声，萌萌哒' },
    { id: '103', name: '度米朵', description: '温柔女声，儿童故事' },
    { id: '106', name: '度博文', description: '情感男声，新闻播报' },
    { id: '110', name: '度小童', description: '萌宝男声，可爱童声' },
  ];

  const getVoiceName = (voiceId) => {
    const voice = voiceOptions.find((v) => v.id === voiceId);
    return voice ? voice.name : '度丫丫';
  };

  const handleVoiceChange = async (voiceId) => {
    setSelectedVoice(voiceId);
    setShowVoicePicker(false);
    await AsyncStorage.setItem(TTS_VOICE_KEY, voiceId);
    voiceService.setBaiduTtsConfig({ voiceName: voiceId });
    ToastManager.success(`已切换为 ${getVoiceName(voiceId)}`);
  };

  const handleRequestLocation = async () => {
    setLocStatus('定位中...');
    try {
      const granted = await requestLocationPermission();
      await markLocationPermissionAsked();
      if (!granted) {
        setLocationEnabled(false);
        setLocStatus('权限被拒绝，请前往系统设置开启');
        setShowLocationService(true);
        ToastManager.warning('定位权限被拒绝，请前往系统设置开启');
        return;
      }

      const position = await getCurrentPosition();
      const { latitude, longitude } = position.coords;
      const gcj =
        (await convertWgs84ToGcj02ViaAmap(latitude, longitude)) ||
        wgs84ToGcj02(latitude, longitude);
      const info = await getLocationInfo(gcj.longitude, gcj.latitude);

      setLocationEnabled(true);
      setLocStatus(
        `已定位：${info.city || '未知城市'} (${gcj.latitude.toFixed(
          4,
        )}, ${gcj.longitude.toFixed(4)})`,
      );
      await AsyncStorage.setItem(LOCATION_STATUS_KEY, 'enabled');

      setShowLocationService(false);
      ToastManager.success('定位成功');
    } catch (error) {
      setLocationEnabled(false);
      setLocStatus('定位失败，请检查网络或稍后再试');
      setShowLocationService(true);
      ToastManager.error('定位失败，请检查网络或稍后再试');
    }
  };

  const formatSize = bytes => {
    if (bytes > 1024 * 1024) {
      return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
    }
    if (bytes > 1024) {
      return `${(bytes / 1024).toFixed(1)} KB`;
    }
    return `${bytes} B`;
  };

  const refreshCacheSize = async () => {
    try {
      const cacheDir = RNFS.CachesDirectoryPath;
      const files = await RNFS.readDir(cacheDir);
      let total = 0;
      for (const file of files) {
        if (file.isFile()) {
          total += file.size;
        }
      }
      setCacheSize(formatSize(total));
    } catch (error) {
      setCacheSize('--');
    }
  };

  const handleClearCache = async () => {
    try {
      ToastManager.info('正在清理缓存...');
      
      // 异步执行清理操作，避免UI卡顿
      setTimeout(async () => {
        try {
          // 清理AsyncStorage中的缓存记录
          const cacheKeys = ['audio_cache', 'image_cache'];
          await Promise.allSettled(
            cacheKeys.map(key => AsyncStorage.removeItem(key).catch(err => {
              console.warn(`清理${key}失败:`, err);
            }))
          );
          
          // 清理缓存文件
          await removeCacheFiles();
          
          // 刷新缓存大小
          await refreshCacheSize();
          
          ToastManager.success('缓存已清理');
        } catch (error) {
          console.error('清理缓存失败:', error);
          ToastManager.error('清理缓存失败，请稍后重试');
          // 即使失败也刷新缓存大小
          await refreshCacheSize();
        }
      }, 100);
    } catch (error) {
      console.error('启动清理缓存失败:', error);
      ToastManager.error('启动清理失败');
    }
  };

  const removeCacheFiles = async () => {
    try {
      const cacheDir = RNFS.CachesDirectoryPath;
      
      // 检查目录是否存在
      const dirExists = await RNFS.exists(cacheDir);
      if (!dirExists) {
        return;
      }
      
      const entries = await RNFS.readDir(cacheDir);
      
      // 使用 Promise.allSettled 确保所有删除操作都尝试执行
      const results = await Promise.allSettled(
        entries.map(async (entry) => {
          try {
            // 检查文件是否存在
            const exists = await RNFS.exists(entry.path);
            if (!exists) {
              return { success: true, path: entry.path, skipped: true };
            }
            
            // 删除文件或目录
            await RNFS.unlink(entry.path);
            return { success: true, path: entry.path };
          } catch (err) {
            console.warn(`⚠️ 删除失败: ${entry.name}`, err.message);
            return { success: false, path: entry.path, error: err };
          }
        })
      );
      
      // 统计清理结果
      const successCount = results.filter(r => r.status === 'fulfilled' && r.value.success && !r.value.skipped).length;
      const skipCount = results.filter(r => r.status === 'fulfilled' && r.value.skipped).length;
      const failCount = results.filter(r => r.status === 'rejected' || (r.status === 'fulfilled' && !r.value.success)).length;
      
    } catch (error) {
      console.error('❌ 清理缓存文件失败:', error);
      throw error; // 向上抛出错误让调用者处理
    }
  };

  return (
    <SafeTabBarWrapper style={{ backgroundColor: COLORS.background.secondary }}>
      <ScrollView
        style={styles.container}
        contentContainerStyle={styles.content}
      >
        {showLocationService && (
          <View style={styles.section}>
            <Text style={styles.sectionTitle}>定位服务</Text>
            <View style={styles.card}>
              <SettingItem title="旅行定位" description={locStatus}>
                <TouchableOpacity
                  style={styles.primaryButton}
                  onPress={handleRequestLocation}
                  activeOpacity={0.75}
                >
                  <Text style={styles.primaryButtonText}>
                    {locationEnabled ? '重新定位' : '开启定位'}
                  </Text>
                </TouchableOpacity>
              </SettingItem>
            </View>
          </View>
        )}

        <View style={styles.section}>
          <Text style={styles.sectionTitle}>讲解偏好</Text>
          <View style={styles.card}>
            <SettingItem
              title="自动播放讲解"
              description="进入景点详情自动播放语音讲解"
            >
              <View style={styles.switchWrapper}>
                <Switch
                  value={autoPlayEnabled}
                  onValueChange={handleToggleAutoPlay}
                  trackColor={{ false: '#dcdcdc', true: '#ffb997' }}
                  thumbColor={autoPlayEnabled ? '#ff6b35' : '#f4f3f4'}
                />
              </View>
            </SettingItem>
            <View style={styles.divider} />
            <TouchableOpacity
              style={styles.settingItem}
              onPress={() => setShowVoicePicker(!showVoicePicker)}
              activeOpacity={0.7}
            >
              <View style={styles.settingTextWrapper}>
                <Text style={styles.settingTitle}>播报员声音</Text>
                <Text style={styles.settingDescription}>选择您喜欢的语音播报声音</Text>
              </View>
              <Text style={styles.actionText}>{getVoiceName(selectedVoice)}</Text>
            </TouchableOpacity>
            {showVoicePicker && (
              <View style={styles.voicePickerContainer}>
                {voiceOptions.map((voice) => (
                  <TouchableOpacity
                    key={voice.id}
                    style={[
                      styles.voiceOption,
                      selectedVoice === voice.id && styles.voiceOptionSelected,
                    ]}
                    onPress={() => handleVoiceChange(voice.id)}
                    activeOpacity={0.7}
                  >
                    <View style={styles.voiceOptionContent}>
                      <Text
                        style={[
                          styles.voiceOptionName,
                          selectedVoice === voice.id && styles.voiceOptionNameSelected,
                        ]}
                      >
                        {voice.name}
                      </Text>
                      <Text style={styles.voiceOptionDescription}>{voice.description}</Text>
                    </View>
                    {selectedVoice === voice.id && (
                      <View style={styles.checkMark}>
                        <Text style={styles.checkMarkText}>✓</Text>
                      </View>
                    )}
                  </TouchableOpacity>
                ))}
              </View>
            )}
          </View>
        </View>

        <View style={styles.section}>
          <Text style={styles.sectionTitle}>偏好设置</Text>
          <View style={styles.card}>
            <TouchableOpacity
              style={styles.settingItem}
              onPress={handleClearCache}
              activeOpacity={0.7}
            >
              <View style={styles.settingTextWrapper}>
                <Text style={styles.settingTitle}>清理缓存</Text>
                <Text style={styles.settingDescription}>
                  包括图片、语音讲解等
                </Text>
              </View>
              <Text style={styles.actionText}>{cacheSize}</Text>
            </TouchableOpacity>
          </View>
        </View>

        <View style={styles.section}>
          <Text style={styles.sectionTitle}>隐私与安全</Text>
          <View style={styles.card}>
            <TouchableOpacity
              style={styles.settingItem}
              onPress={() => ToastManager.info('隐私政策敬请期待')}
              activeOpacity={0.7}
            >
              <Text style={styles.settingTitle}>隐私政策</Text>
              <Text style={styles.actionText}>查看</Text>
            </TouchableOpacity>
            <View style={styles.divider} />
            <TouchableOpacity
              style={styles.settingItem}
              onPress={() => ToastManager.info('用户协议敬请期待')}
              activeOpacity={0.7}
            >
              <Text style={styles.settingTitle}>用户协议</Text>
              <Text style={styles.actionText}>查看</Text>
            </TouchableOpacity>
          </View>
        </View>
      </ScrollView>
    </SafeTabBarWrapper>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: COLORS.background.secondary,
  },
  content: {
    paddingBottom: 32,
  },
  section: {
    marginHorizontal: 16,
    marginTop: 20,
  },
  sectionTitle: {
    fontSize: 16,
    fontWeight: '600',
    color: COLORS.text.primary,
    marginBottom: 12,
  },
  card: {
    borderRadius: 16,
    backgroundColor: COLORS.background.card,
    paddingHorizontal: 20,
    paddingVertical: 12,
    ...SHADOWS.sm,
  },
  settingItem: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingVertical: 12,
    minHeight: Platform.OS === 'ios' ? 44 : 48,
  },
  divider: {
    height: StyleSheet.hairlineWidth,
    backgroundColor: COLORS.border.light,
  },
  settingTextWrapper: {
    flex: 1,
    paddingRight: 16,
  },
  settingTitle: {
    fontSize: 15,
    color: COLORS.text.primary,
    fontWeight: '500',
  },
  settingDescription: {
    marginTop: 4,
    fontSize: 12,
    color: COLORS.text.quaternary,
  },
  actionText: {
    fontSize: 14,
    color: COLORS.primary,
    fontWeight: '600',
  },
  primaryButton: {
    backgroundColor: COLORS.primary,
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderRadius: 8,
    minHeight: Platform.OS === 'ios' ? 36 : 32,
    justifyContent: 'center',
    alignItems: 'center',
  },
  primaryButtonText: {
    color: COLORS.white,
    fontSize: 14,
    fontWeight: '600',
  },
  switchWrapper: {
    minWidth: Platform.OS === 'ios' ? 66 : 56,
    paddingRight: Platform.OS === 'ios' ? 4 : 0,
    alignItems: 'flex-end',
    justifyContent: 'center',
  },
  voicePickerContainer: {
    marginTop: 8,
    paddingTop: 8,
    borderTopWidth: StyleSheet.hairlineWidth,
    borderTopColor: COLORS.border.light,
  },
  voiceOption: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingVertical: 12,
    paddingHorizontal: 12,
    marginVertical: 4,
    borderRadius: 8,
    backgroundColor: COLORS.background.secondary,
  },
  voiceOptionSelected: {
    backgroundColor: COLORS.primaryLight,
    borderWidth: 1,
    borderColor: COLORS.primary,
  },
  voiceOptionContent: {
    flex: 1,
    paddingRight: 8,
  },
  voiceOptionName: {
    fontSize: 15,
    fontWeight: '600',
    color: COLORS.text.primary,
  },
  voiceOptionNameSelected: {
    color: COLORS.primary,
  },
  voiceOptionDescription: {
    fontSize: 12,
    color: COLORS.text.quaternary,
    marginTop: 2,
  },
  checkMark: {
    width: 24,
    height: 24,
    borderRadius: 12,
    backgroundColor: COLORS.primary,
    alignItems: 'center',
    justifyContent: 'center',
  },
  checkMarkText: {
    color: COLORS.white,
    fontSize: 14,
    fontWeight: 'bold',
  },
});


